package com.ml4ai.backend.web.util;

import com.ml4ai.backend.consts.Const;
import com.ml4ai.backend.dto.*;
import com.ml4ai.backend.utils.Bean2Map;
import com.ml4ai.backend.utils.PropertyMapper;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Created by uesr on 2018/9/9.
 */
public class MapSpec {

    public static Map<String, Object> user2map(UserDTO user) {
        Map<String, Object> map = new Bean2Map().addIgnores(Const.getNotCopyAuditFields()).map(user);
        return map;
    }

    public static Map<String, Object> task2map(TaskDTO task) {
        Map<String, Object> map = new Bean2Map().addIgnores(Const.getNotCopyAuditFields()).addPropMapper(
                new PropertyMapper<>("starter", MapSpec::user2map),
                new PropertyMapper<>("taker", MapSpec::user2map),
                new PropertyMapper<>("site", MapSpec::site2map)
        ).map(task);
        return map;
    }

    public static Map<String, Object> intraCityDistributionTask2map(IntraCityDistributionTaskDTO intraCityDistributionTask) {
        Map<String, Object> map = new Bean2Map().addIgnores(Const.getNotCopyAuditFields()).addPropMapper(
                new PropertyMapper<>("starter", MapSpec::user2map),
                new PropertyMapper<>("taker", MapSpec::user2map),
                new PropertyMapper<>("site", MapSpec::site2map)
        ).map(intraCityDistributionTask);
        return map;
    }

    public static Map<String, Object> site2map(SiteDTO site) {
        Map<String, Object> map = new Bean2Map().addIgnores(Const.getNotCopyAuditFields()).addPropMapper(
                new PropertyMapper<>("parent", MapSpec::site2map)
        ).map(site);
        return map;
    }

    public static Map<String, Object> mapCrawlTask(CrawlTaskDTO crawlTaskDTO) {
        Map<String, Object> map = new Bean2Map().addIgnores(Const.getNotCopyAuditFields()).addPropMapper(
                new PropertyMapper<>("seeds", (List<TextDTO> seeds) -> MapSpec.mapList(seeds, MapSpec::mapText)),
                new PropertyMapper<>("regex", (List<TextDTO> regex) -> MapSpec.mapList(regex, MapSpec::mapText))
        ).map(crawlTaskDTO);
        return map;
    }

    public static <T, K> List<Object> mapList(List<K> ks, Function<K, T> converter) {
        return ks.stream().map(converter).collect(Collectors.toList());
    }

    public static Map<String, Object> mapText(TextDTO textDTO) {
        Map<String, Object> map = new Bean2Map().addIgnores(Const.getNotCopyAuditFields()).map(textDTO);
        return map;
    }

}
